package com.lisence.util;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.calmcar.adas.apiserver.AdasConf;
import com.calmcar.adas.apiserver.out.ActiveSuccessListener;
import com.calmcar.adas.conf.Constant;
import com.calmcar.adas.serverman.LaneCarServerManager;
import com.calmcar.adas.serverman.LdwServerManager;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by lelexiao on 2018/4/16.
 */
public class LisenceManager {
    private long lisenceLimitDate =2592000/3;
    private SharedPreferences spf=null;
    LaneCarServerManager ldwServerManager;

    public ActiveSuccessListener getActiveSuccessListener() {
        return activeSuccessListener;
    }

    public void setActiveSuccessListener(ActiveSuccessListener activeSuccessListener) {
        this.activeSuccessListener = activeSuccessListener;
    }

    ActiveSuccessListener activeSuccessListener;

    public LisenceManager(LaneCarServerManager  ldwServerManager, Context mContext) {
        this.ldwServerManager = ldwServerManager;
        this.mContext = mContext;
        spf=mContext.getSharedPreferences("adas_hmsl", Activity.MODE_PRIVATE);
        getDeviceDetail();
    }

    public LisenceManager(Context mContext) {
        this.mContext = mContext;
        spf=mContext.getSharedPreferences("adas_hmsl", Activity.MODE_PRIVATE);
        getDeviceDetail();
    }

    public int  checkLicenceDate() {
        getDeviceDetail();
        int result=-1;
        String oldImei=spf.getString("imei","###");
        //如果imei存在
        if("###".equals(imei) || imei==null ){
            if(!"###".equals(oldImei) ){
                imei=oldImei;
            }else{
                return result;
            }
        }
        String hsml=spf.getString("hsml","000");
        if(! hsml.equals("000")){
            result=ldwServerManager.putHsml( imei,hsml);
            Log.i("adas_hsml_log","激活成功----"+result);
            if(result==0){
                AdasConf.IS_ACTIVE=true;
                if(activeSuccessListener!=null ){
                    activeSuccessListener.onActiveCallBack(""+1+ result);
                }
            }else{//缓存失效
                Thread thread=new Thread(new Runnable() {
                    @Override
                    public void run() {
                        checkLicence();
                    }
                });
                thread.start();
            }
        }else{
            Thread thread=new Thread(new Runnable() {
                @Override
                public void run() {
                    checkLicence();
                }
            });
            thread.start();
        }
        return result;
    }


    /**
     * 厂商ID+Device_id+version
     */

    private Context mContext;
    private TelephonyManager telephonyManager;
    private String imei,deptID;

    public  void getDeviceDetail() {
        //IMEI（imei）
        telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        try {
            imei = telephonyManager.getDeviceId();
        } catch (SecurityException e) {
            e.printStackTrace();
            if(activeSuccessListener!=null ){
                activeSuccessListener.onActiveCallBack(4+"");
            }
//            showToast(mContext,"获取imei出错");
            Log.i("adas_hsml_log","未获取imei权限");
            imei="###";
        }
        deptID = "96k01";
    }

    private void checkLicence() {
        try {
            URL url = new URL(Constant.url);
            HttpURLConnection urlConn= (HttpURLConnection) url.openConnection();
            urlConn.setConnectTimeout(60000);
            urlConn.setReadTimeout(15000);
            urlConn.setRequestMethod("POST"); // 指定使用POST请求方式
            urlConn.setDoInput(true); // 向连接中写入数据
            urlConn.setDoOutput(true); // 从连接中读取数据
            urlConn.setRequestProperty("Charset", "UTF-8");
            String param="deptID="+deptID +"&imei="+ imei ;
            urlConn.getOutputStream().write(param.getBytes());
            int code = urlConn.getResponseCode();
            if (code == 200) {
                InputStream inputStream =urlConn.getInputStream();
                String result= convertStreamToString(inputStream);
                JSONObject object = new JSONObject( result);
                String status = object.getString("status");
                if (status.equals("03") || status.equals("04")) {
                    String hsml= object.getString("ActivationCode");
                    spf.edit().putString("hsml",hsml).commit();
                    int res=ldwServerManager.putHsml( imei,hsml);
                    if(activeSuccessListener!=null ){
                        if(res==0){
                            AdasConf.IS_ACTIVE=true;
                            spf.edit().putString("imei",imei).commit();
                            activeSuccessListener.onActiveCallBack(1+"");
                        }else{
                            activeSuccessListener.onActiveCallBack("0"+1+res);
                        }
                    }
                    Log.i("adas_hsml_log","激活成功"+res);
                }else if(status.equals("01") || status.equals("02")  ) {
                    showToast(mContext,"未经授权，激活失败");
                    Log.i("adas_hsml_log","未经授权，激活失败");
                    if(activeSuccessListener!=null ){
                        activeSuccessListener.onActiveCallBack(2+"");
                    }
                }
            }else{
                showToast(mContext,"服务器错误，激活失败");
                Log.i("adas_hsml_log","服务器错误，激活失败");
                if(activeSuccessListener!=null ){
                    activeSuccessListener.onActiveCallBack(3+"");
                }
            }
        } catch (Exception e) {
            if(activeSuccessListener!=null ){
                activeSuccessListener.onActiveCallBack(5+"");
            }
            showToast(mContext,"网络请求错误");
            Log.i("adas_hsml_log","网络请求错误");
            e.printStackTrace();
        }

    }

    public String convertStreamToString(InputStream input){
        StringBuffer out = new StringBuffer();
        try {
            byte[] b = new byte[4096];
            for (int n; (n = input.read(b)) != -1;) {
                out.append(new String(b, 0, n));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return   out.toString();
    }


    public void showToast(Context mContext,String msg){
        if(Looper.getMainLooper().getThread() == Thread.currentThread()){
            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
        }else{
            Looper.prepare();
            Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
            Looper.loop();
        }

    }









}
